import React, { Component } from 'react'
import { withRouter } from 'react-router'
import { Form, PageHeader, Divider, Badge, Button, Modal } from 'antd'
import * as BomService from '../../axios/Bom'
import SearchForm from './SearchFormDetails';
import { BasicLayout, BasicLayoutSearch } from '../../components/BasicLayout'
import { BasicPagination, compareNum, TableCustomize, openSuccessModal, openModalMessage, compareString } from '../../components/TableCustomize'
class ComparisonBatchNumber extends Component {
    state = {
        columns: [
            {
                title: '序号',
                dataIndex: 'id',
                width: 50,
                align: 'center',
                // render: (text, record, index) => <span>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</span>,
                render: (text, record, index) => index + 1
            },

            {
                title: '物料编码',
                width: 150,
                dataIndex: 'partCode',
                sorter: (a, b) => compareString(a.partCode, b.partCode),
                editable: true,
                render: (text, record, index) =>
                    <div>
                        {
                            record.partChangeAttitude == 1 ? <Badge status="success" text={'新增'} /> : record.partChangeAttitude == 2 ? <Badge status="default" text={'取消'} /> : record.partChangeAttitude == 3 ? <Badge status="warning" text={'属性变化'} /> : record.partChangeAttitude == 4 ? <Badge status="processing" text={'回仓'} /> : null
                        }
                        <div>{text}</div>
                    </div>
            },
            {
                title: '图号',
                width: 150,
                // allowEllipsis: true,
                dataIndex: 'paperCode',
                sorter: (a, b) => compareString(a.paperCode, b.paperCode)
            },
            {
                title: '机型',
                width: 100,
                dataIndex: 'model',
                sorter: (a, b) => compareString(a.model, b.model)
            },
            {
                title: '物料名称',
                width: 100,
                dataIndex: 'partName',
                sorter: (a, b) => compareString(a.partName, b.partName)
            },
            {
                title: '物料规格',
                width: 150,
                dataIndex: 'partSpec',
                sorter: (a, b) => compareString(a.partSpec, b.partSpec)
            },
            {
                title: '数量',
                width: 80,
                dataIndex: 'partNeedNum',
                sorter: (a, b) => compareNum(a.partNeedNum, b.partNeedNum),
            },
            {
                title: '版本',
                width: 80,
                dataIndex: 'version',
                sorter: (a, b) => compareString(a.version, b.version),
            },
            {
                title: '仓库',
                width: 100,
                dataIndex: 'storeName',
                sorter: (a, b) => compareString(a.storeName, b.storeName),
            },
            {
                title: '装配组别名称',
                width: 150,
                dataIndex: 'assemblyGroup',
                sorter: (a, b) => compareString(a.assemblyGroup, b.assemblyGroup),
            },
            {
                title: '装配组别代码',
                width: 150,
                dataIndex: 'groupCode',
                sorter: (a, b) => compareString(a.groupCode, b.groupCode),
            },
            { dataIndex: '999' }
        ],
        loading: false,
        dataSource: [
        ],
        dataSourceTwo: [
        ],
        list1: [],
        list2: [],
        advanced: false,
        searchItem: {},
        batchNoId: [],
        pageSize: 10,
        pageNum: 1,
        total: 0,
        pageSizeTwo: 10,
        pageNumTwo: 1,
        totalTwo: 0,
        locationData: {},
        batchNos: []
    }
    componentDidMount() {
        let data = this.props.history.data ? this.props.history.data : JSON.parse(localStorage.getItem('ComparisonBatchNumber'))
        // console.log('接收路由传参', data)
        let batchNoId = []
        let batchNos = []
        data.forEach((value, index, array) => {
            batchNoId.push(value.id)
            batchNos.push(value.batchNo)
        })
        this.setState({
            locationData: { id1: batchNoId[0], id2: batchNoId[1] },
            batchNoId: batchNoId,
            batchNos: batchNos
        }, () => { this.produceOrderCompare(); })
    }
    produceOrderCompare = () => {
        this.setState({ loading: true });
        const { locationData, searchItem } = this.state;
        const data = { ...locationData, ...searchItem }
        BomService.produceOrderCompare(data).then(res => {
            this.setState({ loading: false })
            if (res.data.code !== 200) {
                openModalMessage('warning', res.data.msg);
                return;
            }
            this.setState({
                // dataSource: res.data.data[0].list1,
                // dataSourceTwo: res.data.data[0].list2,
                list1: res.data.data[0].list1,
                list2: res.data.data[0].list2,
                total: res.data.data[0].list1.length,
                totalTwo: res.data.data[0].list2.length,
            }, () => { this.fetch(); this.fetchTwo() });
        }).catch(err => {
            openModalMessage('error', err.message);
        })
    }
    //初始化加载数据
    fetch = (pageNum = 1, pageSize = 100) => {
        const { list1 } = this.state
        let data = [...list1]
        let pagingS = data.splice(pageNum == 1 ? 0 : pageNum > 1 ? pageNum * pageSize - pageSize : 0, pageSize)
        // console.log(pagingS, pageSize, pageNum > 1 ? pageNum * pageSize - pageSize : 0);
        this.setState({
            pageNum: pageNum,
            pageSize: pageSize,
            dataSource: pagingS
        })
    }

    fetchTwo = (pageNumTwo = 1, pageSizeTwo = 100) => {
        const { list2 } = this.state
        let data = [...list2]
        let pagingS = data.splice(pageNumTwo == 1 ? 0 : pageNumTwo > 1 ? pageNumTwo * pageSizeTwo - pageSizeTwo : 0, pageSizeTwo)
        this.setState({
            pageNumTwo: pageNumTwo,
            pageSizeTwo: pageSizeTwo,
            dataSourceTwo: pagingS
        })
    }
    handleSearch = value => {
        console.log('这是什么', value);
        this.setState({ searchItem: value }, () => { this.produceOrderCompare() });
    };
    onHandleAdvanced = () => {
        this.setState({ advanced: !this.state.advanced })
    }
    resetForm = () => {
        this.formSearch && this.formSearch.resetFields();
        this.setState({ searchItem: {} }, this.produceOrderCompare());
    }
    // 导出
    export = () => {
        // const { locationData } = this.state;
        Modal.confirm({
            title: '默认导出数据较多，需要较长时间，确认全部导出吗？',
            onOk() {
                // BomService.exportProductDetailList().then((res) => {
                //     //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
                //     let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
                //     // 创建A标签
                //     let link = document.createElement('a')
                //     link.style.display = 'none'
                //     link.href = url
                //     // 设置的下载文件文件名
                //     const fileName = decodeURI('生产订单-详情页面');
                //     // 触发点击方法
                //     link.setAttribute('download', fileName)
                //     document.body.appendChild(link)
                //     link.click()
                // })
                // let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
                // let link = document.createElement('a')
                // link.style.display = 'none'
                // link.href = url
                // const fileName = decodeURI('生产');
                // link.setAttribute('download', fileName)
                // document.body.appendChild(link)
                // link.click()
            },
            onCancel() { },
        })
    }
    componentWillUnmount() {
        this.setState = () => {
            return
        }
    }
    render() {
        const { dataSourceTwo, columns, pageNum, pageSize, total, pageNumTwo, pageSizeTwo, totalTwo, batchNos, dataSource, loading, selectedRowKeys, advanced, searchItem } = this.state
        const rowSelection = {
            type: 'checkbox',
            columnWidth: 40,
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows,
                    selectedRowKeys: selectedRowKeys,
                })
            },
        }
        return (
            <div>
                <BasicLayoutSearch>
                    <PageHeader
                        style={{ padding: '4px 24px' }}
                        onBack={() => this.props.history.push({ pathname: '/Bom' })}
                        title={'对比数据'}>
                    </PageHeader>
                    <Divider />
                    <SearchForm onSearch={this.handleSearch}
                        onClick={this.onHandleAdvanced}
                        advanced={advanced} searchItem={searchItem}
                        resetForm={this.resetForm}
                        ref={node => (this.formSearch = node)}
                    />
                </BasicLayoutSearch>
                <BasicLayout
                    name={`${batchNos[0]} 与 ${batchNos[1]} BOM清单数据对比`}
                    icon="table"
                    buttons={
                        [
                            <Button key={1} onClick={this.export} type='primary' icon='download'>导出</Button>,
                        ]
                    }

                >
                    <div style={{ display: 'flex' }}>
                        <div style={{ width: '50%' }}>
                            <TableCustomize
                                columns={columns}
                                rowKey={(record) => record.id}
                                dataSource={dataSource}
                                pagination={false}
                                loading={loading}
                                scroll={{ x: true, y: 600 }}
                                allowDrafting={true}
                                rowClassName={(record, index) => {
                                    return (['editable-row', record.sort !== null ? 'editable-row123' : '', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
                                }}
                            />
                            <BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
                        </div>
                        <div style={{ width: '50%' }}>
                            <TableCustomize
                                columns={columns}
                                rowKey={(record) => record.id}
                                dataSource={dataSourceTwo}
                                pagination={false}
                                loading={loading}
                                scroll={{ x: true, y: 600 }}
                                allowDrafting={true}
                                rowClassName={(record, index) => {
                                    return (['editable-row', record.sort !== null ? 'editable-row123' : '', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
                                }}
                            />
                            <BasicPagination pageNum={pageNumTwo} pageSize={pageSizeTwo} total={totalTwo} loadData={this.fetchTwo} />
                        </div>
                    </div>
                </BasicLayout>

            </div>
        )
    }
}
export default Form.create()(withRouter(ComparisonBatchNumber))